//
//  ConfirmDeliveryViewController.swift
//  Box
//
//  Created by mn on 2025/3/31.
//
import UIKit

class ConfirmDeliveryViewController: BaseViewController {
    var stashModel: StashModel?
    private let dispatchGroup = DispatchGroup()
    
    private let tableView = UITableView(frame: .zero, style: .grouped)
    let submitOrderView = SubmitOrderView()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "提货确认"
        tableView.backgroundColor = .fromHex("#F4F6F8")
        view.addSubview(submitOrderView)
        submitOrderView.backgroundColor = .white
        submitOrderView.snp.makeConstraints { make in
            make.height.equalTo(100)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
        }
        submitOrderView.button.addAction {
            [weak self] in
            guard let self else { return }
            createOrder()
        }
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(nav.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(submitOrderView.snp.top)
        }

        tableView.bounces = false
        tableView.dataSource = self
        tableView.delegate = self
        tableView.contentInsetAdjustmentBehavior = .never
        tableView.separatorColor = .clear
        tableView.registerCells([SelectAddressCell.self,
                                 GoodsCell.self])
        dispatchGroup.enter()
        getDefaultAddress()
        
        dispatchGroup.enter()
        getOrderFreight()
        
        dispatchGroup.notify(queue: .main) {
            if let stashModel = self.stashModel{
                self.submitOrderView.priceLabel.text = String(format: "¥ %.2f", Float(stashModel.price + self.freight) * 0.01)
            }
            self.tableView.reloadData()
        }
        
    }
    var defaultAddressData: AddressData?
    func getDefaultAddress(){
        APIService.request(api: .getDefaultAddress) {
            [weak self] (result, response) in
            defer { self?.dispatchGroup.leave() }
            if result.success, let model: DefaultAddressResponse = Decoder.data(response) {
                self?.defaultAddressData = model.data
            }
        }
    }
    
    var freight: Int = 0
    func getOrderFreight() {
        guard let stashModel else {
            dispatchGroup.leave()
            return
        }
        APIService.request(api: .getOrderFreight(storeIdList: [stashModel.id])) {
            [weak self] (result, response) in
            defer { self?.dispatchGroup.leave() }
            if result.success, let model: FreightModel = Decoder.data(response) {
                self?.freight = model.data
            }
        }
    }
    func createOrder(){
        guard let stashModel,let defaultAddressData else {
            return
        }
        APIService.request(api: .createOrder(storeIdList: [stashModel.id],
                                             addressId: defaultAddressData.id)) {
            [weak self] (result, response) in
            if result.success {
                self?.toast("下单成功，请到个人中心查看")
                self?.navigationController?.root()
            }
        }
    }
    
}
extension ConfirmDeliveryViewController: UITableViewDataSource,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        1
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        2
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0{
            let cell: SelectAddressCell = tableView.cell(indexPath)
            if let defaultAddressData{
                cell.addressView.data = defaultAddressData
            }
            return cell
        }
        let cell: GoodsCell = tableView.cell(indexPath)
        cell.stashModel = self.stashModel
        cell.freightView.priceLabel.text = String(format: "¥ %.2f", Float(freight) * 0.01)
        return cell
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let titleLabel = UILabel()
        titleLabel.text = section == 0 ? "  提货信息" : " 商品信息"
        titleLabel.textColor = .init(hex: "#333333")
        titleLabel.font = UIFont.systemFont(ofSize: 15, weight: .medium)
        return titleLabel
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        45
    }
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        UIView()
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        0.01
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0{
            let vc = AddressViewController()
            vc.selectAddress = {
               [weak self] data in
                self?.defaultAddressData = data
                self?.tableView.reloadData()
            }
            navigationController?.push(vc)
        }
    }
}
